import { App } from "vue";

const PressEnter = {
	install(app: App) {
		app.directive("enter-submit", {
			mounted(el, binding) {
				const handleKeyDown = (event: KeyboardEvent) => {
					if (event.key === "Enter") {
						event.preventDefault(); // 阻止事件的默认行为
						binding.value(); // 调用绑定的回调函数
					}
				};
				window.addEventListener("keydown", handleKeyDown, true);
				el._enterSubmitHandler = handleKeyDown; // 保存事件处理函数的引用
			},
			unmounted(el) {
				const handleKeyDown = el._enterSubmitHandler;
				window.removeEventListener("keydown", handleKeyDown, true);
				delete el._enterSubmitHandler; // 移除保存的事件处理函数的引用
			},
		});
	},
};

export default PressEnter;
